package leetcode;


public class TestMain {
    static class ListNode {
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode head2 = getMidNode(node1);
        System.out.println(head2.val);
        ListNode newHead = reverse(head2);
        ListNode cur = node1;
        while (cur.next.next != null) {
            cur = cur.next;
        }
        cur.next = null;
        ListNode head = merge(node1, newHead);
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
    }

    // 找到中点
    public static ListNode getMidNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        return slow;
    }

    // 反转链表，返回头节点
    public static ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = cur.next;
        while (cur != null) {
            cur.next = pre;
            pre = cur;
            cur = next;
            if (cur != null) {
                next = cur.next;
            }

        }

        return pre;
    }

    public static ListNode merge(ListNode l1, ListNode l2) {

        ListNode dummy = new ListNode(0);
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        ListNode cur = dummy;
        while (cur != null && cur1 != null && cur2 != null) {
            cur.next = cur1;
            cur1 = cur1.next;
            cur = cur.next;

            cur.next = cur2;
            cur2 = cur2.next;
            cur = cur.next;

            // cur1.next = l2;
            // cur1 = l2;
            // l2 = l2.next;

            // cur2.next = l1;
            // cur2 = l1;
            // l1 = l1.next;
        }


        return dummy.next;
    }

}
